﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
using System.Threading.Tasks;

namespace CodeAPP.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class UploadFileController : ControllerBase
    {
        private readonly IWebHostEnvironment env;

        public UploadFileController(IWebHostEnvironment env)
        {
            this.env = env;
        }

        [HttpPost("/uploadFile")]
        public async Task<IActionResult> Upload(IFormFile formFile)
        {
            var FolderPath = $"/UploadFile/{DateTime.Now.ToString("yyyyMMdd")}";
            var FilePath = $"/{DateTime.Now.ToString("yyyyMMddHHmmssfff")}{Path.GetExtension(formFile.FileName)}";

            //创建文件夹
            if(!Directory.Exists($"{env.WebRootPath}{FolderPath}"))
                Directory.CreateDirectory($"{env.WebRootPath}{FolderPath}");

            using (FileStream file = new FileStream($"{env.WebRootPath}{FolderPath}{FilePath}", FileMode.OpenOrCreate))
            {
                await formFile.CopyToAsync(file);
            }

            return Ok(new
            {
                filePath = $"{FolderPath}{FilePath}"
            });
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> JsonFile()
        {
            var filePath = $"{env.WebRootPath}/json.json";

            MemoryStream memoryStream = new MemoryStream();
            using (FileStream stream = new FileStream(filePath, FileMode.OpenOrCreate))
            {
                byte[] bytes = new byte[stream.Length];

                await stream.ReadAsync(bytes, 0, bytes.Length);

                memoryStream.Write(bytes, 0, bytes.Length);

                //await stream.CopyToAsync(memoryStream);


                return File(memoryStream.ToArray(), "application/jpeg", "abc.jpg");
            }
        }
    }
}
